package com.egg.ylt.activity;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.provider.Settings;
import android.view.View;
import android.widget.LinearLayout;

import com.egg.ylt.R;
import com.egg.ylt.Utils.StringUtil;
import com.egg.ylt.pojo.CheckAppVersionEntity;
import com.egg.ylt.presenter.impl.CheckAppVersionPresenterImpl;
import com.egg.ylt.receiver.NetStatusReceiver;
import com.egg.ylt.updateAppUtils.UpdateAppVersionUtil;
import com.egg.ylt.view.ICheckAppVersionView;
import com.yonyou.framework.library.base.BaseActivity;
import com.yonyou.framework.library.bean.ErrorBean;
import com.yonyou.framework.library.common.utils.ToastUtil;

import butterknife.BindView;

public class ACT_AppStart extends BaseActivity<CheckAppVersionPresenterImpl> implements ICheckAppVersionView {

    @BindView(R.id.ll_loading_view)
    LinearLayout llLoadingView;

    private TimeCount mTime;
    private String appVersionCode;
    private String updateUrl = "https://sd-picture-oss.oss-cn-beijing.aliyuncs.com/app-release.apk";
    private String desc;
    private NetStatusReceiver netReceiver;
    private String code;

    private int updateType =0;

    private boolean mNet = false;

    @Override
    protected void getBundleExtras(Bundle extras) {

    }

    @Override
    protected int getContentViewLayoutID() {
        return R.layout.act_app_start;
    }

    @Override
    protected View getLoadingTargetView() {
        return llLoadingView;
    }

    @Override
    protected void initViewsAndEvents() {
        // 获取版本号
        //版本号
        appVersionCode = StringUtil.getAppVersionName(mContext);

//        netReceiver = new NetStatusReceiver();
//        setRegisterReceiver(netReceiver);
//        setNetListener();

        //倒计时
        timeToHome();

    }

    @Override
    protected boolean isApplyStatusBarTranslucency() {
        return false;
    }

    @Override
    protected boolean isBindEventBusHere() {
        return false;
    }

    @Override
    protected boolean toggleOverridePendingTransition() {
        return false;
    }

    @Override
    protected TransitionMode getOverridePendingTransitionMode() {
        return null;
    }

    @Override
    protected boolean isApplyKitKatTranslucency() {
        return false;
    }

    @Override
    public void showBusinessError(ErrorBean error) {

    }

    @Override
    public void checkType(CheckAppVersionEntity entity) {
        if (entity == null){
            return;
        }

        code = entity.getCode();
        updateUrl = entity.getUrl();
        desc = entity.getDesc();
        getCheckVersion(code);
    }

    /**
     * 倒计时
     */
    public void timeToHome(){
        mTime = new TimeCount(1000, 1000);
        mTime.start();
    }

    /**
     * 根据返回的版本号，是否需要更新
     * 1000：当前的客户端是最新版本
     * 1001：有新版本，需要强制更新
     * 1002：有新版本，不需要强制更新
     */
    public void getCheckVersion(String code){
        switch (code){
            case "1000":
                //开启倒计时
                timeToHome();
                break;
            case "1001":
                showNormalDialog(code, desc, "版本更新");
                break;
            case "1002":
                showNormalDialog(code, desc, "版本更新");
                break;
        }
    }

    /**
     * 版本更新
     * 系统自带的dialog
     */
    private void showNormalDialog(final String code, String desc, String title){
        /* @setIcon 设置对话框图标
         * @setTitle 设置对话框标题
         * @setMessage 设置对话框消息提示
         * setXXX方法返回Dialog对象，因此可以链式设置属性
         */
        final AlertDialog.Builder normalDialog = new AlertDialog.Builder(mContext);
        normalDialog.setTitle(title);
        normalDialog.setMessage(desc);
        normalDialog.setPositiveButton("确定",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (mNet){
                            //确定更新
                            dialog.cancel();
                            UpdateAppVersionUtil.downLoadApk(mContext,ACT_AppStart.this, updateUrl);
                        }else{
                            ToastUtil.makeText(mContext, "网络异常，请检查网络", false);
                        }
                    }
                });
        if ("1002".equals(code) || "1003".equals(code)){
            normalDialog.setCancelable(true);// 设置是否可以通过点击Back键取消，或者点击区域以外的地方
            normalDialog.setNegativeButton("取消",
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            if ("1003".equals(code)){
                                //取消更新
                                dialog.cancel();
                                finish();
                            }else{
                                //取消更新
                                dialog.cancel();
                                //跳转到首页
                                readyGo(ACT_HomePage.class);
                            }
                        }
                    });
        }else{
            normalDialog.setCancelable(false);// 设置是否可以通过点击Back键取消，或者点击区域以外的地方
        }

        // 显示
        normalDialog.show();
    }

    //设置发送短信倒计时
    class TimeCount extends CountDownTimer {

        public TimeCount(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onTick(long millisUntilFinished) {
        }

        @Override
        public void onFinish() {
            //跳转到首页
            readyGo(ACT_HomePage.class);
            finish();
        }
    }

    /**
     * 权限申请回调方法
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == UpdateAppVersionUtil.CAMERA_REQUEST_CODE) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                mPresenter.checkAppVersion(appVersionCode, "android");
            } else {
                // Permission Denied
            }
        }else if (requestCode == UpdateAppVersionUtil.INSTALL_PACKAGES_REQUESTCODE){
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    UpdateAppVersionUtil.installApk(mContext);
                    finish();
                } else {
                    Intent intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES);
                    startActivityForResult(intent, UpdateAppVersionUtil.GET_UNKNOWN_APP_SOURCES);
                }
        }

    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            //Android8.0设置允许安装未知来源权限后的返回
            case UpdateAppVersionUtil.INSTALL_PACKAGES_REQUESTCODE:
                //安装apk
                UpdateAppVersionUtil.installApk(mContext);
                break;
            //不知道为什么，不管是否点击安装、取消，返回的resultCode都是0，即RESULT_CANCELED，待查
            case RESULT_CANCELED:
                ToastUtil.makeText(mContext, "您拒绝了安装权限，安装失败", false);
                finish();
                break;
            default:
                break;
        }

    }

    public void setRegisterReceiver(NetStatusReceiver netReceiver){
        IntentFilter filter = new IntentFilter();
        filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        registerReceiver(netReceiver, filter);
    }
    public void setNetListener(){
        netReceiver.setNetStateListener(new NetStatusReceiver.INetStatusListener() {

            @Override
            public void getNetState(int state) {
                if (state == NetStatusReceiver.NETSTATUS_INAVAILABLE) {
                    mNet = false;
                    ToastUtil.makeText(mContext, "网络异常", false);
                } else {
                    mNet = true;
                    if (updateType == 0){
                        updateType = 1;
                        //请求查看服务器是否需要更新app
                        //先判断是否有读取sd卡权限
                        boolean permissions = UpdateAppVersionUtil.requestPhotosPermissions(mContext, ACT_AppStart.this);
                        if (permissions){
                            mPresenter.checkAppVersion(appVersionCode, "android");
                        }
                    }else {
                        showNormalDialog("1003", "您的网络发生变化，是否继续更新", "版本更新");
                    }
                }
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
//        unregisterReceiver(netReceiver);
    }

}
